<template>
	<view class="dynamic-form">
		<!--  可配置区域 -->
		<view class="dynamic-form-data">
			<view v-for="(field, index) in feildData" :key="index" class="dynamic-form-item">
				<view v-if="field.component != 'List'" class="dynamic-form-item__row">
					<view class="dynamic-form-item__label">
						<uni-text>{{ field.label }}</uni-text>
						<uni-text v-if="!field.readOnly && field.required" class="required">*</uni-text>
					</view>
					<view class="dynamic-form-item__desc">
						<DynamicField :fieldKey="field.key" :formData="formData" :field="field" :isEdit="isEdit"
							@update-form-data="updateFormData" />
					</view>
				</view>
				<view v-else class="dynamic-form-item__row list">
					<view class="dynamic-form-item__label">
						<uni-text>{{ field.label }}</uni-text>
						<uni-text v-if="!field.readOnly && field.required" class="required">*</uni-text>
					</view>
					<!-- 商品列表 -->
					<view class="data-list">
						<view v-for="(value, key) in selectGoods" :key="key">
							<view class="data-item">
								<img :src="value.image || defaultImage" @click="goToDetail(item)" class="data-image"
									@error="handleImageError(value)" />
								<view class="data-info" @click="goToDetail(value)">
									<text class="data-name">{{ value.name }}</text>
									<text class="data-info-detail">
										价格:￥{{ value.price }}
									</text>
								</view>
								<view @click="addToOrderList">

								</view>
								<view>
									<uni-number-box v-model="value.buyNum" @change="changeValue(value)" :min="0"
										:max="value.stock"></uni-number-box>
								</view>
							</view>
						</view>
					</view>

					<view class="price_info">
						已选 {{totalNum}} 件，总价：￥{{sumprice}}
					</view>
				</view>
				<view v-if="formData[field.key] && errors[field.key]" class="dynamic-form-item__error">
					<text class="error">{{ errors[field.key] }}</text>
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="flex flex-wrap diygw-col-24 flex-direction-column diygw-bottom">
			<view class="flex diygw-col-24">
				<button style="color: #fbf7f7 !important" @tap="navigateTo" data-type="page" data-url="/pages/index"
					class="diygw-btn gradual-blue radius-xl flex-sub margin-xs button-button-clz">取消</button>
				<button @click="onSave"
					class="diygw-btn cyan radius-xl flex-sub margin-xs button-button-clz">确认</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import DynamicField from '@/components/fields/DynamicField.vue';
	import orderFeildData from '@/common/data/orders/storeOrderFeild.js';
	import dataDictionary from '@/common/data/dataDictionary.js';
	export default {
		data() {
			return {
				formData: {},
				updateFlag: false,
				feildData: orderFeildData,
				isEdit: true,
				goodSourceOpt: dataDictionary.goods.source,
				selectGoods: {},
				totalNum: 0,
				sumprice: 0,
				storeOpt: []
			};
		},
		components: {
			DynamicField,
		},

		computed: {
			...mapGetters({
				userInfo: 'user/info',
				hasLogin: 'user/hasLogin'
			}),
		},

		onLoad(options) {
			if (options?.goods) {
				this.selectGoods = JSON.parse(options.goods);
			}
			this.initFormData();
			// 获取用户权限
			if (this.userInfo.roles) {
				let storeIds = [];
				Object.entries(this.userInfo.roles).forEach(([key, value]) => {
					for (let i = 0; i < value.length; i++) {
						if (storeIds.includes(value[i].storeId)) {
							continue;
						} else {
							this.storeOpt.push({
								value: value[i].storeId,
								text: value[i].storeName,
							});
							storeIds.push(value[i].storeId);
						}
					}
				});
			}

			if (this.feildData) {
				for (let i = 0; i < this.feildData.length; i++) {
					let obj = this.feildData[i];
					if (obj.key === 'goodsSource') {
						obj.options = this.goodSourceOpt;
					} else if (obj.key === 'storeId') {
						obj.options = this.storeOpt
					}
				}
			}
			this.updateSelectData();
		},

		methods: {
			
			initFormData(){
				this.formData.userName = this.userInfo.name;
				this.formData.createdBy = this.userInfo.employeeId;
				this.formData.createAt = new Date();
				this.formData.updatedBy = this.userInfo.employeeId;
				this.formData.updateAt = this.formData.createAt;
				this.formData.storeId = this.userInfo.storeId;
				this.formData.storeName = this.userInfo.storeName;
				this.formData.goods = [];
				;
			},
			
			sumSelectPrice() {
				let price = 0;
				Object.keys(this.selectGoods).forEach(key => {
					price = price + this.selectGoods[key].buyNum * this.selectGoods[key].price
				})
				this.sumprice = price;
			},

			changeValue(value) {
				if (value.buyNum === 0) {
					delete this.selectGoods[value.id];
				}
				this.updateSelectData();
			},

			updateSelectData() {
				this.totalNum = Object.keys(this.selectGoods).length;
				this.sumSelectPrice();
			},

			updateFormData(key, newFormData) {
				if (this.formData[key] == newFormData[key]) {
					return;
				}
				console.log("修改前的值======" + key + ":", this.formData[key])
				this.formData = newFormData; // 更新父组件的值
				console.log("修改后的值======" + key + ":", this.formData[key])
				if (!this.feildData) {
					return;
				}
				for (let i = 0; i < this.feildData.length; i++) {
					let obj = this.feildData[i];
					if (!obj.relations || !obj.relations[key]) {
						continue;
					}
					if (!obj.relations[key].inclues(this.formData[key])) {
						obj.isShow = false;
					} else {
						obj.isShow = true;
					}
				}
			},

			// 保存
			async onSave() {
				if (!this.formData.id) {
					this.formData.createdAt = new Date();
				}
				if(!this.selectGoods){
					// 成功处理
					uni.showToast({
						title: "商品为空",
						duration: 1500
					});
					return;
				}else{
					Object.values(this.selectGoods).forEach(value => {
						value.buyPrice = value.price * value.buyNum;
						this.formData.goods.push(value);
					})
				}
				this.formData.updatedAt = new Date();
				this.$api.saveStoreOrder(this.formData).then(result => {
					;
					if (!this.formData.id && result && Number.isInteger(result)) {
						this.formData.id = result;
						this.handleSubmit()
					}else{
						// 成功处理
						uni.showToast({
							title: "保存成功",
							duration: 3000
						});
					} 
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "保存失败!",
						duration: 3000
					});
					return;
				})
			},
			
			// 使用示例
			async  handleSubmit() {
			  await this.showToastAndThen({
				title: '添加成功',
				icon: 'success',
				duration: 3000
			  });
			  uni.removeStorageSync("orderGoods")
			  // Toast关闭后执行的逻辑
			  uni.navigateTo({
			  	url:"/pages/index/index"
			  })
			},
			
			// 封装工具函数
			showToastAndThen(options) {
			  return new Promise((resolve) => {
				uni.showToast({
				  title: options.title,
				  icon: options.icon || 'none',
				  duration: options.duration || 1500,
				  mask: options.mask || false
				});
				
				setTimeout(() => {
				  resolve();
				}, options.duration || 1500);
			  });
			},
			

			// 取消
			onCancel() {
				uni.navigateBack();
			},

		}
	};
</script>


<style lang="less" scoped>
	@import url("@/common/css/dynamic-form.less");
	@import url("@/common/css/list_new.less");

	.list {
		display: block !important;
	}

	.data-item::after {
		content: " " !important;
		/* 右箭头 */
		font-size: 0rpx;
		/* 箭头大小 */
		color: #999;
		/* 箭头颜色 */
		margin-left: 0rpx;
		/* 箭头与文本的间距 */
	}

	.data-list {
		padding-left: 0rpx !important;
		padding-right: 0rpx !important;
		padding-bottom: 200rpx !important;
	}

	.price_info {
		float: right;
		/* padding-right: 20px; */
		font-size: 14px;
		position: fixed;
		bottom: 146rpx;
		right: 40rpx;
		background-color: #fff;
		z-index: 900;
	}
</style>